package me.zhengjie.config.sftp;

import com.jcraft.jsch.*;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

@Component
public class SftpConnector {
    @Value("${remote.host}")
    private String host;

    @Value("${remote.port:22}")
    private int port;

    @Value("${remote.username}")
    private String username;

    @Value("${remote.password}")
    private String password;

    @Value("${remote.connect-timeout:5000}")
    private int connectTimeout;

    public Session createSession() throws JSchException {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setTimeout(connectTimeout);
        session.connect();
        return session;
    }

    public ChannelSftp createChannel(Session session) throws JSchException {
        Channel channel = session.openChannel("sftp");
        channel.connect(connectTimeout);
        return (ChannelSftp) channel;
    }
}